<!doctype html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      #myform { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
       input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
       button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
    </style>
  </head>
  <body >
      <div>
    <div id="content">
    </div>
  </div>
  <div id="myform">
  <input id="input" type="text" autocomplete="off" /><button onclick="say()">Send</button>
  </div>
    <script src="/socket.io/socket.io.js"></script>
  <script>
    // 建立连接
    var socket = io.connect('http://localhost:3000');
    // 监听 message 会话
    socket.on('message', function (data) {
      let html = document.createElement('p')
      html.innerHTML = `系统消息：<span>${data.hello}</span>`
      document.getElementById('content').appendChild(html)
      console.log(data);
    });
    var inputText=document.getElementById('input');
    inputText.addEventListener("keyup",function(e){
        if(e.keyCode==13){
            say();
        }

    })
    // 按钮点击事件
    function say() {
      let t = inputText.value
      if (!t) return
      let html = document.createElement('p')
      html.innerHTML = `你细声说：<span>${t}</span>`
      document.getElementById('content').appendChild(html)
      inputText.value="";
      socket.emit('say', { my: t});
    }
    // 监听 news 会话
    socket.on('news', function (data) {
      console.log(data);
      let html = document.createElement('p')
      html.innerHTML = `小乖说：<span>我知道了，你说“${data.hello}”</span>`
      document.getElementById('content').appendChild(html)
    });
    // 监听吃饭会话
    socket.on('eating', function (data) {
      console.log(data);
      let html = document.createElement('p')
      html.innerHTML = `小乖说：${data.hello}`
      document.getElementById('content').appendChild(html)
    });
  </script>
  </body>
</html>
